package com.lagou.controller;

import com.lagou.mo.Article;
import com.lagou.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    ArticleService articleService;
    
    @RequestMapping("/index")
    public String indexPage(HttpServletRequest httpServletRequest, Model model){
    
        Integer pageSize = 2;
        Integer pageNum = 0;
        if(httpServletRequest.getParameter("pageNum")!=null && pageNum>=0) {
            pageNum = Integer.valueOf(httpServletRequest.getParameter("pageNum"));
        }
        Pageable pageable =  pageable = PageRequest.of(pageNum, pageSize, Sort.Direction.DESC, "id");

        Page<Article> articlePage = articleService.listArticle(pageable);
        List<Article> articleList = articlePage.getContent();
        model.addAttribute("pageNum", articlePage.getNumber());
        model.addAttribute("articleList", articleList);
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        
        return "client/index";
    }
    
    @RequestMapping("/last-page")
    public String lastPage(HttpServletRequest httpServletRequest, Model model){
        
        Pageable pageable =  pageable = PageRequest.of(0, 2, Sort.Direction.ASC, "id");
        
        Page<Article> articlePage = articleService.listArticle(pageable);
        List<Article> articleList = articlePage.getContent();
        model.addAttribute("pageNum", articlePage.getTotalPages()-1);
        model.addAttribute("articleList", articleList);
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        
        return "client/index";
    }
    
   
}
